//
//  YDVideoPreview.swift
//  YDPhotoPicker
//
//  Created by alyadan on 16/8/16.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import MVVM_BaseViewController
import AVFoundation
import AVKit
import Photos
import SnapKit

import RxSwift
import RxCocoa

class YDVideoPreviewViewController: MVVM_BaseViewController {
    
    let videoPlayerVC = AVPlayerViewController()
    var currentVCModel:YDVideoPreviewVCModel {
        get{
            return vcModel.value as! YDVideoPreviewVCModel
        }
    }
    
    
    override func setupUI() {
        
        self.addChild(videoPlayerVC)
        videoPlayerVC.didMove(toParent: self)
        view.addSubview(videoPlayerVC.view)
        
        view.backgroundColor = UIColor.black
        setNavgationItem(withImageName: nil, orTitle: "选择", location: .right)
        customRightBarButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        customRightBarButton?.setTitleColor(UIColor.white, for: .normal)
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        videoPlayerVC.view.snp.updateConstraints {[weak self] (make) in
            make.left.right.bottom.equalTo(self!.view)
            make.top.equalTo(self!.view).offset(64)
        }
    }
    
    
    override func bindModelData() {
        currentVCModel.player.asObservable()
            .observeOn(MainScheduler.instance)
            .bind {[unowned self] (x: AVPlayer?) in
                self.videoPlayerVC.player = x
            }
            .disposed(by: disposeBag)
    }
    
}

class YDVideoPreviewVCModel: MVVM_BaseVCModel {
    override func viewController(vcIndex: Int) -> MVVM_BaseViewController? {
        return YDVideoPreviewViewController()
    }
    
    override func onTapNavRightBtn() {
        sendVideoAction()
    }
    
    var parentVCModel:YDPhotoShowAlbumVCModel{
        return parentViewModel as! YDPhotoShowAlbumVCModel
    }
    
    var player = Variable<AVPlayer?>(nil)
    
    var videoAsset:PHAsset?
    
    var videoLocalURL:NSURL?
    
    init(videoAsset:PHAsset?, parentViewModel:MVVM_BaseViewModel){
        self.videoAsset = videoAsset
        super.init(parentViewModel: parentViewModel)
        
        if let x = videoAsset{
            let option = PHVideoRequestOptions()
            PHImageManager.default().requestAVAsset(forVideo: x, options: option, resultHandler: { (asset, _, _) in
                if let x = asset as? AVURLAsset{
                    self.videoLocalURL = x.url as NSURL?
                    self.player.value = AVPlayer(url: x.url)
                }
            })
            
        }
    }
    
    override func setupModel() {
        viewControllerTitle.value = "视频预览"
    }
    
    func sendVideoAction(){
        parentVCModel.parentVCModel?.videoCallBack?(videoAsset, videoLocalURL)
        self.MVVM_modelController?.dismiss(animated: true, completion: nil)
    }
    
}
